<template>
  <!-- 告警处理 -->
  <BaseMainSlot :show-tab="false" :showBtnBox="false">
    <template v-slot:search-box>
      <el-collapse v-model="activeName" accordion>
        <el-collapse-item name="1">
          <template slot="title">
            <div class="select-btns search-btns" @click.stop="changeSelect()">
              <i class="el-icon-circle-check"></i>
              <p v-if="activeName === '1'">收起筛选</p>
              <p v-if="activeName === ''">展开筛选</p>
            </div>
          </template>
          <div class="search-btn search-btns" @click.stop="search()">
            <i class="el-icon-circle-check"></i>
            <p>查询</p>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">鱼塘名称</div>
            <el-select filterable clearable v-model="fishPondId" filterable clearable>
              <el-option v-for="item in fishPondArr" :key="item.fishPondId" :label="item.pondName"
                :value="item.fishPondId" />
            </el-select>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">数据类型</div>
            <el-select filterable clearable v-model="dataTypeId" filterable clearable>
              <el-option v-for="(item, index) in dataTypeList" :key="index" :value="item.dataTypeId"
                :label="item.dataTypeName" />
            </el-select>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">数据项</div>
            <el-select filterable clearable v-model="dataItemId" filterable clearable>
              <el-option v-for="(item, index) in dataitemlist" :key="index" :value="item.iotDataItemId"
                :label="item.dataItemName" />
            </el-select>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">告警日期</div>
            <el-date-picker v-model="buildDateTime" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" value-format="yyyy-MM-dd" clearable />
          </div>
          <!-- 查询报错 -->
          <!-- <div class="select-box-content">
            <div class="select-box-content-name">处理日期</div>
            <el-date-picker
              v-model="disposeTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择"
              clearable />
          </div> -->
        </el-collapse-item>
      </el-collapse>
    </template>
    <template v-slot:tab-select></template>
    <template v-slot:table-box>
      <el-table v-show="nowselecttype === 0" v-loading="false" :data="tableData" stripe border height="88%"
        @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" :selectable="(row) => { return !row.selectable }" /> -->
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column v-for="item, index in formDatalists" :key="index" :type="`${item.porp}`" :prop="`${item.porp}`"
          :label="item.name" :min-width="'130'" :column-key="`${item.porp}`">
          <template v-if="scope.row[`${item.porp}`] !== undefined" slot-scope="scope">
            <span v-if="item.type !== 'TimePicker'">{{ scope.row[`${item.porpName}`] || scope.row[`${item.porp}`] || '——'
            }}</span>
            <span v-else-if="item.linkage === 'breedingFlag'">{{ scope.row[`${item.porpName}`] ? '是' : '否' || '——'
            }}</span>
            <span v-else>{{ scope.row[`${item.porp}`] ? scope.row[`${item.porp}`] : '——' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <!--
            -->
            <el-button type="warning" v-if="scope.row.fishPondId && judgePermission(18, 'handle')" plain size="small"
              :disabled="scope.row.disposeStatus" @click="handlingmmessage(scope.row)">处理</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize"
        @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
    </template>
    <template v-slot:dialog>
      <el-dialog title="处理结果" :visible.sync="dialogVisible" width="30%">
        <div class="zhdialog">
          <el-form :model="formData" :rules="rules" ref="formData">
            <el-form-item label prop="disposeContent" class="w100p">
              <el-input v-model="formData.disposeContent" type="textarea" :rows="4" placeholder="请输入处理意见" />
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button class="cancelbtn" @click="dialogVisible = false">取 消</el-button>
          <el-button class="savebtn" type="primary" @click="clickqueren('formData')">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="前后一小时数据" :visible.sync="dialogVisibletwo" width="50%">
        <div>
          <!-- <div>{{ nowwarringmessage }}</div> -->
          <!-- <div></div> -->
          <div style="margin-top:10px;">
            <zhechart :nowwidth="'100%'" :nowheight="'300px'" :cdata="echartlist" :fontcolor="'#0c0f0f'"
              :font-size="12" />
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button class="cancelbtn" @click="dialogVisibletwo = false">取 消</el-button>
          <el-button class="savebtn" @click="dialogVisibletwo = true">确 定</el-button>
        </span>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>
<script>
import Pagination from "@/components/Pagination";
// import userreq from "@/api/user/index";
// import AddEditDialog from "./components/add-edit-dialog.vue";
import zhechart from "@/components/Echarts/components/linechart/chart.vue";
import selectbut from "@/components/selectbutton/index.vue";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import fishPondApi from "@/api/basic-info-manage/fishPond";
import dataItemApi from "@/api/basic-info-manage/data-item-manage/index";
import dataTypeApi from "@/api/basic-info-manage/data-type-manage";
import nowpagereq from "@/api/monitoring-alarm/historical-alarm-record/index";
import { mymixin } from "@/utils/mixins";
import SearchBox from "@/components/SearchBox";
import * as echarts from "echarts";

import { mapGetters } from "vuex";
export default {
  name: "AlarmHandling",
  components: {
    Pagination,
    BaseMainSlot,
    selectbut,
    zhechart,
    SearchBox,
  },
  mixins: [mymixin],
  data () {
    return {
      rules: {
        disposeContent: [
          { required: true, message: "处理意见不能为空", trigger: "blur" }
        ]
      },
      // 可选择数据类型
      dataTypeList: [],
      // 可选择批次
      batchList: [],
      // 前后一小时数据
      dialogVisibletwo: false,
      echartlist: {
        xAxisdata: [],
        xData: ["前后一小时数据"],
        seriesData: []
      },
      nowwarringmessage: {},
      // -----------
      defaulthandinglist: ["已处理完成", "未处理", "其他"],
      defaulthandindex: 0,
      dialogVisible: false,
      nowselecttype: 0, // 0为物联自动告警 2为手动记录告警 1为数值告警
      dataitemlist: [],
      searchlist: {
        dataItemId: "",
        date: ""
      },
      // 选择类型
      selectbutlist: [
        { name: "物联自动告警" }
        // { name: "设备异常告警" }
        // { name: "手动记录告警" },
      ],
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      nowselectedList: [],
      // 可选择所有地块
      alarmTypeList: [],
      // 鱼塘
      fishPondArr: [],
      // 查询 start
      batchNo: "",
      alarmTypeId: "",
      dataTypeId: "",
      dataItemId: "",
      buildDateTime: "",
      disposeTime: "",
      fishPondId: "",
      dataTypeId: "",
      dataItemId: "",
      // 查询 end
      editObject: {},
      showAddEditDialog: false,
      formDatalists: [
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "fishPondName",
          typeObj: {},
          name: "鱼塘名称",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "messageInfo",
          typeObj: {},
          name: "告警信息"
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "dataItemName",
          porpName: "buildingName",
          linkage: true,
          typeObj: {},
          name: "告警数据项"
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "alarmPresetValue",
          porpName: "columnName",
          typeObj: {},
          name: "预设告警值"
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "actualAlarmValue",
          typeObj: {},
          name: "实际告警值"
        },
        {
          type: "TimePicker", // input Select Checkbox TimePicker
          porp: "happenTime",
          typeObj: {},
          name: "发生时间"
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          porp: "dataTypeName",
          typeObj: {
            // list: [
            //   { name: "是", value: "是" },
            //   { name: "否", value: "否" }
            // ],
            // listName: ["name", "value"]
          },
          name: "告警数据类型"
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "staffNameList",
          typeObj: {},
          name: "告警联系人"
        },
        // {
        //   type: "Status", // input Select Checkbox TimePicker
        //   porp: "disposeStatus",
        //   typeObj: {},
        //   name: "告警信息状态"
        // },
        // {
        //   type: "TimePicker", // input Select Checkbox TimePicker
        //   porp: "disposeTime",
        //   typeObj: {},
        //   name: "处理时间"
        // }
      ],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {},
  created () {
    this.routerParams = this.$route.query ? this.$route.query : {}
    this.fishPondId = this.routerParams.fishPondId ? this.routerParams.fishPondId : undefined
    this.search();
  },
  mounted () {
    this.getselecltlist();
  },
  methods: {
    // 获取当前拥有类型表格
    getTableDataList () {
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          fishPondId: this.fishPondId || undefined,
          alarmTypeId: this.alarmTypeId || undefined,
          dataTypeId: this.dataTypeId || undefined,
          dataItemId: this.dataItemId || undefined,
          // disposeTime: this.disposeTime || undefined,
          disposeStatus: false
        }
      };
      if (this.buildDateTime) {
        params.entity.startTime = this.buildDateTime[0] + ' 00:00:00';
        params.entity.endTime = this.buildDateTime[1] + ' 24:00:00'
      }
      // params.entity['fishPondId'] = this.routerParams && this.routerParams.fishPondId  // 这样写会导致每次请求的时候，都会从路由参数取值覆盖查询条件 改为在created周期给this.fishPondId传值
      nowpagereq.queryPageList(params, false).then(res => {
        this.loading = false;
        if (!res.success) {
          this.$message.error(res.message || "当前告警历史表格获取失败");
        }
        res.data.content.forEach(item => {
          item.staffNameList = item.staffNameList.join(',')
        })
        let data = res.data.content;
        // 赋值总条数
        this.totalSize = res.data.totalElements;
        // 赋值数组
        this.tableData = data;
        this.addblankmet();
        this.resetActionBar();
        this.routerParams = {}
      });
    },
    // 表格中的标签
    filterTag (value, row) {
      return row.disposeStatus === value;
    },
    // 表格中的标签
    filtername (value) {
      if (value) {
        return "已处理";
      } else {
        return "未处理";
      }
    },
    // 处理意见
    handlingmmessage (e) {
      this.formData = {};
      this.dialogVisible = true;
      this.formData.alarmMessageId = e.alarmMessageId;

      // if (this.nowselecttype === 1) {
      //   if (e.alarmMessageId) {
      //     this.formData.alarmMessageId = e.alarmMessageId;
      //   }
      // }
      // if (this.nowselecttype === 0) {
      //   if (e.alarmMessageId) {
      //     this.formData.alarmMessageId = e.alarmMessageId;
      //   }
      // }
    },
    // 默认处理意见
    defaulthandmet (i) {
      if (i === 0) {
        this.formData.disposeContent = "已处理完成";
      } else if (i === 1) {
        this.formData.disposeContent = "未处理";
      } else {
        this.formData.disposeContent = "";
      }
    },
    // 点击弹框确认
    clickqueren (formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          // this.formData.disposeContent = '';
          // this.formData.disposeStatus = true;
          // console.log(this.formData);
          // return;
          nowpagereq.editlist(this.formData).then(res => {
            if (res.success) {
              this.search();
              this.$message.success("处理成功");
              this.dialogVisible = false;
            } else {
              this.$message.error(res.message || "处理失败");
            }
          });
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    // 获取不同类型的表格数据
    gettabletype (i) {
      this.nowselecttype = i;
      if (i === 0) {
      } else if (i === 1) {
        // this.getTableDataListtwo();
      } else if (i === 2) {
        console.log(i);
      }
    },
    // 查看详细数据
    getalrmmessage (e) {
      this.dialogVisibletwo = true;
      // this.nowwarringmessage = {}
      // let disposeTime = new Date(e.disposeTime)
      let berforTime = this.getbeforertime(e.disposeTime);
      let afterTime = this.getaftertime(e.disposeTime);
      this.nowwarringmessage = {
        nowtime: e.disposeTime,
        berforTime: berforTime,
        afterTime: afterTime,
        dataItemId: e.dataItemId,
        dataItemName: e.dataItemName
      };
      this.getnewmessage();
      // console.log(this.nowwarringmessage)
    },
    // 获取折线图图数据
    getnewmessage () {
      let params = {
        startTime: this.nowwarringmessage.berforTime,
        endTime: this.nowwarringmessage.afterTime,
        dataItemId: this.nowwarringmessage.dataItemId
      };
      nowpagereq.getdataitemcollectquery(params).then(res => {
        let listone = res.data;
        // console.log(listone)
        let xAxisdata = [];
        let serdata = [];
        listone.forEach(item => {
          xAxisdata.push(item.collectDatetime.substring(5, 16));
          serdata.push(item.value);
        });
        this.echartlist = {
          xAxisdata: xAxisdata,
          xData: ["前后一小时数据"],
          seriesData: [
            {
              name: this.nowwarringmessage.dataItemName,
              type: "line",
              data: serdata,
              itemStyle: {
                normal: {
                  color: new echarts.graphic.LinearGradient(1, 0, 0, 1, [
                    { offset: 0, color: "#04FA99" },
                    { offset: 1, color: "#3EACE5" }
                  ])
                }
              }
            }
          ]
        };
      });
    },
    // 获取前一小时数据
    getbeforertime (originDate) {
      const dt = new Date(originDate);
      const y = dt.getFullYear();
      const m = (dt.getMonth() + 1 + "").padStart(2, "0");
      const d = (dt.getDate() + "").padStart(2, "0");
      const hh = (dt.getHours() - 1 + "").padStart(2, "0");
      const mm = (dt.getMinutes() + "").padStart(2, "0");
      const ss = (dt.getSeconds() + "").padStart(2, "0");
      return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
    },
    // 获取后一小时数据
    getaftertime (originDate) {
      const dt = new Date(originDate);
      const y = dt.getFullYear();
      const m = (dt.getMonth() + 1 + "").padStart(2, "0");
      const d = (dt.getDate() + "").padStart(2, "0");
      const hh = (dt.getHours() + 1 + "").padStart(2, "0");
      const mm = (dt.getMinutes() + "").padStart(2, "0");
      const ss = (dt.getSeconds() + "").padStart(2, "0");
      return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
    },
    // 布尔值格式化
    formatBoolean (row, column, cellValue) {
      var ret = ""; // 你想在页面展示的值
      if (cellValue) {
        ret = "已处理"; // 根据自己的需求设定
      } else if (cellValue === false) {
        ret = "未处理";
      }
      return ret;
    },
    // 获取下拉选择数据
    async getselecltlist () {
      // 获取鱼塘
      const { data: resp } = await fishPondApi.queryByCondition({});
      if (resp !== undefined) {
        this.fishPondArr = resp;
      } else this.fishPondArr = [];
      dataTypeApi.queryExistence().then(res => {
        this.dataTypeList = res.data;
      });
      this.chanbatch({ fishPondId: "" });
    },
    chanbatch (e) {
      // // 获取所有监测数据项
      dataItemApi.queryByCondition({ fishPondId: e.fishPondId }).then(res => {
        this.dataitemlist = res.data;
      });
    },
    handleSelectionChange (list) {
      this.nowselectedList = [];
      this.nowselectedList = list.map(item => {
        return item.ownUnitId;
      });
      if (this.nowselectedList && this.nowselectedList.length > 0)
        this.delActive = true;
      else this.delActive = false;
    },
    delmessage () {
      if (this.nowChanceStau === "del") {
        nowpagereq.dellist(this.nowselectedList).then(res => {
          if (res.success) {
            this.search();
            this.$message.success("删除成功");
          } else {
            this.$message.error("删除失败");
          }
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.zhtabletitle {
  color: #31f7dd;
  margin-bottom: 10px;
}

.zhdialog {
  ::v-deep .el-textarea__inner {
    color: #0c0f0f;
  }
}

::v-deep .el-dialog__body {
  padding: 10px 10px 0px;
}

::v-deep .el-dialog__wrapper {
  .el-dialog {
    width: 20% !important;
    min-width: 20% !important;
    margin-top: 10vh !important;

    .el-dialog__body {
      text-align: center;
    }
  }
}
</style>
